//
//  JCClubMessageVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/27.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCClubMessageVC.h"
#import "JCClubMessageModel.h"
#import "JCClubApi.h"
#import "JCClubInfoMessageCell.h"
#import "UIScrollView+YFMJRefresh.h"
#import "JCClubApi.h"

@interface JCClubMessageVC ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray <JCClubMessageModel *> *messageList;

@property (weak, nonatomic) IBOutlet UITextField *messageInput;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *messageBoardBottom;
@property (weak, nonatomic) IBOutlet UIView *messageBoard;
@property (assign, nonatomic) NSInteger pageIndex;

@end

@implementation JCClubMessageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    [self loadData];
}

- (void)loadData{
    _pageIndex = 1;
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getClubMessageListWithClubID:_clubID page:_pageIndex complete:^(NSError *error, NSArray<JCClubMessageModel *> *messageList) {
        [weakSelf.tableView.mj_header endRefreshing];
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            [weakSelf.hud dismiss];
            [weakSelf.messageList removeAllObjects];
            [weakSelf.messageList addObjectsFromArray:messageList];
            [weakSelf.tableView reloadData];
        }
    }];
}

- (void)loadMore{
    __weak typeof(self)weakSelf = self;
    _pageIndex++;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getClubMessageListWithClubID:_clubID page:_pageIndex complete:^(NSError *error, NSArray<JCClubMessageModel *> *messageList) {
        [weakSelf.tableView.mj_footer endRefreshing];
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            weakSelf.pageIndex -= 1;
        }else{
            [weakSelf.hud dismiss];
            if (messageList.count == 0) {
                weakSelf.pageIndex -= 1;
                [weakSelf.hud showString:NSLocalizedString(@"No more data", @"没有更多数据了") dimissAfterSecond:1];
                [weakSelf.hud showString:@"No More Data" dimissAfterSecond:1];
            }else{
                [weakSelf.messageList addObjectsFromArray:messageList];
                [weakSelf.tableView reloadData];
            }
        }
    }];
}

- (void)initCode{
    self.navigationItem.title = @"Message Board";
    _messageList = [NSMutableArray array];
    
    _sendButton.layer.cornerRadius = 3;
    _sendButton.layer.masksToBounds = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    __weak typeof(self)weakSelf = self;
    _pageIndex = 1;
    [_tableView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
        [weakSelf loadData];
    }];
    [_tableView addNormalFooterWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
    
//    //判断是否管理员
//    if ([[User getUseInfo] clubUserType:_clubID] == ClubUserTypeAdmin) {
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"EDIT" style:UIBarButtonItemStyleDone target:self action:@selector(editMessage:)];
//    }
}

- (void)editMessage:(UIBarButtonItem *)sender{
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _messageList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JCClubInfoMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JCClubMessageCell" forIndexPath:indexPath];
    [cell setMessageModel:_messageList[indexPath.row]];
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[User getUseInfo] clubUserType:_clubID] == ClubUserTypeAdmin) {
        return YES;
    }else{
        return NO;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"Delete";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi deleteMessageWithID:_messageList[indexPath.row].messageID complete:^(NSError *error) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            [weakSelf.hud dismiss];
            [weakSelf.messageList removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }];
}

- (IBAction)sendAction:(UIButton *)sender {
    if (_messageInput.text.length > 0) {
        __weak typeof(self)weakSelf = self;
        [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
        [JCClubApi sendClubMessageWithClubID:_clubID content:_messageInput.text complete:^(NSError *error) {
            if (error) {
                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            }else{
                [weakSelf.hud dismiss];
                [weakSelf loadData];
            }
        }];
    }else{
        [self.hud showErrorWithString:@"Message Is Nil" dimissAfterSecond:2];
    }
    [_messageInput resignFirstResponder];
}

- (void)keyboardWillShow:(NSNotification *)notification{
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height - (kDevice_Is_iPhoneX?35:0);
    _messageBoardBottom.constant = height;
    CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [UIView animateWithDuration:time animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    _messageBoardBottom.constant = 0;
    CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [UIView animateWithDuration:time animations:^{
        [self.view layoutIfNeeded];
        _messageInput.text = @"";
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
